import React, { useCallback, useContext, useMemo, useRef } from 'react';
import { Empty, Icon, message, Popconfirm, Table, Tag, Tooltip } from 'antd';
import PreviewModal from '@/pages/EntryManage/components/Preview/PreviewModal';
import { IMG_TYPE, OFFICE_TYPE, PDF_TYPE } from '@/containers/upload/constant';
import IconFont from '@/components/IconFont';
import EmployeeDetailContext from '@/pages/Organization/EmployeeManage/EmployeeDetail/store/context';
import UploadOss from '@/components/UploadOss';
import { DividerContainer } from '@/molecules';
import authHelper from '@/utils/auth/helper';
import { saveFile } from '@/utils/utils';
import styles from './index.less';

/**
 * 员工档案 - 材料附件
 * @param formData 是一个数组, 数组每个元素是一个 section 数据
 * @param readonly
 * @param uploadMaterialAction
 * @param removeMaterialAction
 */
const MaterialsSection = ({ formData, uploadMaterialAction, removeMaterialAction, employeeInfoData }) => {
    const previewModalRef = useRef();
    const employeeDetailContext = useContext(EmployeeDetailContext);
    const employeeCode = employeeDetailContext?.employeeInfo?.employeeCode;

    // const [fileUploading, setFileUploading] = useState(false);

    // 预览附件
    const handlePreview = useCallback(file => {
        const fileType = file.originName
            .split('.')
            .pop()
            .toLowerCase();
        if (IMG_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'image',
                origin: file.url
            });
        } else if (PDF_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'pdf',
                title: file.keyName,
                origin: file.url
            });
        } else if (OFFICE_TYPE?.includes(fileType)) {
            previewModalRef.current.open({
                type: 'office',
                title: file.keyName,
                origin: file.url,
                encode: true
            });
        }
    }, []);

    // 下载附件
    const handleDownload = useCallback(urlList => {
        urlList.forEach(item => {
            saveFile(item.url, item.originName);
        });
    }, []);

    // 入职材料表格
    const renderTable = useMemo(() => {
        const columns = [
            {
                title: '名称',
                dataIndex: 'categoryName',
                width: '160px'
            },
            {
                title: '类型',
                width: '100px',
                dataIndex: 'resourceType',
                render: (text, record) =>
                    ({ electronMaterial: '电子材料', entityMaterial: '纸质材料' }[record.resourceType])
            },
            {
                title: '状态',
                width: '100px',
                dataIndex: 'resourceStatus',
                render: text => {
                    if (text === 1) {
                        return <Tag color="green">已提供</Tag>;
                    }
                    if (text === 0) {
                        return <Tag>未提供</Tag>;
                    }
                    return null;
                }
            },
            {
                title: '材料',
                className: 'fileColumn',
                render: (files, record) => {
                    const { urlList, categoryCode } = record;
                    const showDelete = authHelper.checkCode('office:orgs:employee:detail:getResource:del');
                    const showPreview = authHelper.checkCode('office:orgs:employee:detail:getResource:get');
                    if (urlList && urlList.length) {
                        return (
                            <div className={styles.filesWrapper}>
                                {urlList.map(file => (
                                    <div key={`${categoryCode}-${file.keyName}`} className="file">
                                        <Tooltip placement="top" title={file.originName}>
                                            <span className="fileName">{file.originName}</span>
                                        </Tooltip>
                                        {showPreview && file.url && (
                                            <span className="preview">
                                                <a onClick={() => handlePreview(file)}>
                                                    <Icon type="eye" />
                                                </a>
                                            </span>
                                        )}
                                        {showDelete && (
                                            <Popconfirm
                                                placement="top"
                                                title="是否删除文件"
                                                onConfirm={() => {
                                                    removeMaterialAction({
                                                        categoryCode,
                                                        employeeCode,
                                                        keyName: file.keyName
                                                    });
                                                }}
                                                okText="是"
                                                cancelText="否"
                                            >
                                                <a className="preview">
                                                    <IconFont icon="iconshanchu" />
                                                </a>
                                            </Popconfirm>
                                        )}
                                    </div>
                                ))}
                            </div>
                        );
                    }
                    return <div className="noFile">未上传</div>;
                }
            },
            {
                title: '操作',
                dataIndex: 'active',
                width: 100,
                render: (text, record) => {
                    const { uploadCountLimit = 0, uploadFormatLimit, uploadFormatTip, urlList, categoryCode } = record;
                    const showUploader =
                        authHelper.checkCode('office:orgs:employee:detail:getResource:upload') &&
                        (!uploadCountLimit ? false : urlList.length < uploadCountLimit);
                    const showDownload =
                        authHelper.checkCode('office:orgs:employee:detail:getResource:download') && !!urlList?.length;

                    return (
                        <DividerContainer>
                            {showUploader && employeeInfoData.serviceStatus !== 6 && (
                                <UploadOss
                                    uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                                    dragAble={false}
                                    checkFileSize={10}
                                    checkFileSizeMsg="文件大小不可超过10M，请重新选择"
                                    categoryCode={categoryCode}
                                    sysCode="OA"
                                    businessCode="SysAvatar"
                                    isSingle
                                    showPreviewFile
                                    checkFileType={uploadFormatLimit}
                                    checkFileTypeMsg={uploadFormatTip}
                                    onUploaded={async (file = []) => {
                                        try {
                                            await uploadMaterialAction({
                                                employeeCode,
                                                materials: [
                                                    {
                                                        categoryCode,
                                                        keyNameAndOpt: [`ADD:${file[0]?.keyName}`]
                                                    }
                                                ]
                                            });
                                        } catch (error) {
                                            message.error(error.message);
                                        }
                                    }}
                                >
                                    <Icon type="upload" className={styles.uploadButton} />
                                </UploadOss>
                            )}
                            {showDownload && (
                                <Icon
                                    type="download"
                                    className={styles.uploadButton}
                                    onClick={() => handleDownload(urlList)}
                                />
                            )}
                        </DividerContainer>
                    );
                }
            }
        ];

        return !formData || formData.length === 0 ? (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
            <Table
                className={styles.paperMaterialsTable}
                rowKey="categoryCode"
                bordered
                columns={columns}
                dataSource={formData}
                pagination={false}
            />
        );
    }, [employeeCode, formData, handleDownload, handlePreview, removeMaterialAction, uploadMaterialAction]);

    // render
    return (
        <>
            <div className="materialTableWrap">{renderTable}</div>
            <PreviewModal height="650px" ref={previewModalRef} />
        </>
    );
};

export default MaterialsSection;
